<?php

namespace wxml\models;

use wxml\models\user\AR\UserAR;

class User extends \yii\base\Object implements \yii\web\IdentityInterface
{
    public $id;
    public $username;
    public $password;
    public $authKey;
    public $access_token;

    public function __construct($value) {
        if($value){
            $this->id=$value['id'];
            $this->username=$value['username'];
            $this->password=$value['password'];
        }
    }

    /**
     * @inheritdoc
     */
    public static function findIdentity($id) {

        $user = (new UserAR())->findOne(['id'=>$id]);
        return new static($user);
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null) {
        $user = (new UserAR())->findOne(array('access_token' => $token));
        if($user['accessToken'] === $token) {
            return $user;
        }

        return null;
    }

    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username) {
        $user = (new UserAR())->findOne(array('name' => $username));

        if(strcasecmp($user['username'], $username) === 0) {
            return new static($user);
        }
        return null;
    }

    /**
     * @inheritdoc
     */
    public function getId() {
        return $this->id;
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey() {
        return $this->authKey;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey) {
        return $this->authKey === $authKey;
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return boolean if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return $this->password === md5(md5($password));
    }
}
